﻿using DrawTools.Serialize;
using System.Windows;
using System.Windows.Media;

namespace DrawTools.Tools
{
    /// <summary>
    /// 直线
    /// </summary>
    [SerializerType(typeof(DrawLineSerializer))]
    public sealed class LineDrawTool : DrawGeometryBase
    {
        #region 字段

        private Point? startPoint, endPoint;

        #endregion 字段
        public LineDrawTool(DrawingCanvas drawingCanvas) : base(drawingCanvas)
        {
            DrawingToolType = DrawToolType.Line;

            // 准备要处理的事件
            CanTouchDown = true;
        }

        #region 鼠标键盘事件

        public override bool OnTouchLeave(Point point, bool isLeaved = false)
        {
            if (!endPoint.HasValue)
                drawingCanvas.DeleteVisual(this);
            else
            {
                geometry = geometry.GetWidenedPathGeometry(Pen);
                Draw();
            }

            if (TouchId == 0 && drawingCanvas.IsMouseCaptured)
                drawingCanvas.ReleaseMouseCapture();

            drawingCanvas.DeleteWorkingDrawTool(this);

            IsFinish = true;

            CanKeyDown = false;
            CanTouchMove = false;
            CanTouchLeave = false;

            return true;
        }

        public override bool OnTouchDown(int touchId, Point point)
        {
            TouchId = touchId;

            if (!startPoint.HasValue)
            {
                drawingCanvas.AddWorkingDrawTool(this);

                startPoint = point;

                geometry = new PathGeometry();

                var figure = new PathFigure { StartPoint = point };
                pathGeometry.Figures.Add(figure);

                CanTouchMove = true;

                if (TouchId != 0 || !drawingCanvas.CaptureMouse())
                    CanTouchLeave = true;

                drawingCanvas.AddVisual(this);

                return true;
            }
            else
                return OnTouchLeave(point);
        }

        public override bool OnTouchMove(Point point)
        {
            var start = startPoint.Value;

            if ((start - point).Length < Pen.Thickness)
                return true;

            var dc = RenderOpen();

            var figure = pathGeometry.Figures[0];
            var line = new LineSegment(point, IsStroked);

            if (endPoint.HasValue)
                figure.Segments[0] = line;
            else
                figure.Segments.Add(line);

            endPoint = point;

            dc.DrawGeometry(null, Pen, geometry);
            dc.Close();

            return true;
        }

        #endregion 鼠标键盘事件
    }
}